import 'dart:html';
import 'dart:math' show Random;
import 'dart:convert' show json;
import 'dart:async' show Future;

//顶级变量
ButtonElement genButton;
SpanElement badgeNameElement;

final String TREASURE_KEY = 'pirateName';

void main() async {
  InputElement inputField = querySelector('#inputName');
  inputField.onInput.listen(updateBadge);
  genButton = querySelector('#generateButton');
  genButton.onClick.listen(generateBadge);
  badgeNameElement = querySelector('#badgeName');

  try {
    await PirateName.readyThePirates();
    //on success
    inputField.disabled = false; //enable
    genButton.disabled = false; //enable
    setBadgeName(getBadgeNameFromStorage());
  } catch (arrr) {
    print('Error initializing pirate names: $arrr');
    badgeNameElement.text = 'Arrr! No names.';
  }
}

void updateBadge(Event e) {
  String inputName = (e.target as InputElement).value;

  setBadgeName(PirateName(firstName: inputName));

  if (inputName.trim().isEmpty) {
    genButton
      ..disabled = false
      ..text = 'Aye! Gimme a name!';
  } else {
    genButton
      ..disabled = true
      ..text = 'Arrr! Write yer name!';
  }
}

void generateBadge(Event e) {
  /// setBadgeName('Anne Bonney');
  setBadgeName(PirateName());
}

void setBadgeName(PirateName newName) {
  if (newName == null) {
    return;
  }
  querySelector('#badgeName').text = newName.pirateName;
  window.localStorage[TREASURE_KEY] = newName.jsonString;
}

//顶级函数：从 localStorage 中获取数据
PirateName getBadgeNameFromStorage() {
  String storedName = window.localStorage[TREASURE_KEY];
  if (storedName != null) {
    return PirateName.fromJSON(storedName);
  } else {
    return null;
  }
}

///声明一个类
class PirateName {
  static final Random indexGen = Random();
  static List names = [];
  static List appellations = [];

  //读取 JSON 数据
  static Future readyThePirates() async {
    String path = 'piratenames.json';
    String jsonString = await HttpRequest.getString(
        path); //await 表达式，你只可以在异步的方法里使用。执行暂停直到 GET 请求完成。（当 Future 在 getString() 完成时返回）
    _parsePirateNamesFromJSON(jsonString);
  }

  //将 JSON 数据存入数组
  static _parsePirateNamesFromJSON(String jsonString) {
    Map pirateNames = json.decode(jsonString);
    names = pirateNames['names'];
    appellations = pirateNames['appellations'];
  }

  ///私有字段 以 _ 开头
  String _firstName;
  String _appellation;

  ///构造方法
  PirateName({String firstName, String appellation}) {
    if (firstName == null) {
      _firstName = names[indexGen.nextInt(names.length)];
    } else {
      _firstName = firstName;
    }
    if (appellation == null) {
      _appellation = appellations[indexGen.nextInt(appellations.length)];
    } else {
      _appellation = appellation;
    }
  }

  ///给 PirateName 类添加一个命名的构造函数。
  PirateName.fromJSON(String jsonString) {
    Map storedName = json.decode(jsonString);
    _firstName = storedName['f'];
    _appellation = storedName['a'];
  }

  //为私有字段提供一个 getter
  String get pirateName =>
      _firstName.isEmpty ? '' : '$_firstName the $_appellation';

  //获取 JSON 字符串
  String get jsonString => json.encode({"f": _firstName, "a": _appellation});

  //重写toString
  String toString() => pirateName;
}
